package nl.hva.three2learn.dao;

import nl.hva.three2learn.model.Topic;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class TopicDaoImpl implements TopicDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public Topic findById(long topicId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Topic t where t.id = :id");
		q.setLong("id", topicId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (Topic) result;
	}

	@Override
	public void save(Topic topic) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(topic);
		session.getTransaction().commit();
	}

	@Override
	public void delete(Topic topic) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.delete(topic);
		session.getTransaction().commit();
	}
}